package d512a.TAKO;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.client.android.CaptureActivity;

import d512a.TAKO.helpers.ColorHelper;
import d512a.TAKO.helpers.DataBaseHelper;

public class HistoryActivity extends ListActivity {
    private LayoutInflater mInflater;
    private Vector<RowData> data;
    private DataBaseHelper db;
    private Cursor cursor;
    RowData rd;

    private String[] title = new String[] {};
    private String[] detail = new String[] {};
    private String[] text = new String[] {};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        data = new Vector<RowData>();

        db = new DataBaseHelper(getApplicationContext());
        try {
            db.openDataBase();
        } catch (SQLException e) {
            throw e;
        } finally {
            db.close();
        }

        populateLists();

        for (int i = 0; i < title.length; i++) {
            try {
                rd = new RowData(text[i], title[i], detail[i]);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            data.add(rd);
        }
        CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.title, data);
        setListAdapter(adapter);
        getListView().setTextFilterEnabled(true);
    }

    public void onListItemClick(ListView parent, View v, int position, long id) {
        Intent basketIntent = new Intent(HistoryActivity.this, BasketActivity.class);
        basketIntent.putExtra("date", title[position]);
        startActivity(basketIntent);

    }

    private class RowData {
        protected String mText;
        protected String mTitle;
        protected String mDetail;

        RowData(String text, String title, String detail) {
            mText = text;
            mTitle = title;
            mDetail = detail;
        }

        @Override
        public String toString() {
            return mText + " " + mTitle + " " + mDetail;
        }
    }

    private class CustomAdapter extends ArrayAdapter<RowData> {
        public CustomAdapter(Context context, int resource, int textViewResourceId,
                        List<RowData> objects) {
            super(context, resource, textViewResourceId, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            TextView title = null;
            TextView detail = null;
            TextView text = null;
            TextView img = null;
            RelativeLayout r = null;
            RowData rowData = getItem(position);
            if (null == convertView) {
                convertView = mInflater.inflate(R.layout.list, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            }
            holder = (ViewHolder) convertView.getTag();
            title = holder.gettitle();
            title.setText(rowData.mTitle);
            detail = holder.getdetail();
            detail.setText(rowData.mDetail);
            r = holder.getRelativeLayout();
            img = (TextView) ((ViewGroup) r).getChildAt(0);
            img.setBackgroundDrawable(getResources().getDrawable(ColorHelper.getColor(Integer.parseInt(rowData.mText))));
            text = (TextView) ((ViewGroup) r).getChildAt(1);
            text.setText(rowData.mText);
            return convertView;
        }

        private class ViewHolder {
            private View mRow;
            private TextView title = null;
            private TextView detail = null;
            private RelativeLayout rel = null;

            // private ImageView i11=null;
            public ViewHolder(View row) {
                mRow = row;
            }

            public TextView gettitle() {
                if (null == title) {
                    title = (TextView) mRow.findViewById(R.id.title);
                }
                return title;
            }

            public TextView getdetail() {
                if (null == detail) {
                    detail = (TextView) mRow.findViewById(R.id.detail);
                }
                return detail;
            }

            public RelativeLayout getRelativeLayout() {
                if (null == rel) {
                    rel = (RelativeLayout) mRow.findViewById(R.id.relLayout);
                }
                return rel;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.product_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        Intent i;
        switch (item.getItemId()) {
        case R.id.menu_item_scan:
            startBarcodeScanner();
            return true;
        case R.id.menu_item_home:
            i = new Intent(getApplicationContext(), HomescreenActivity.class);
            startActivity(i);
            return true;
        case R.id.menu_item_settings:
            i = new Intent(getApplicationContext(), UserInfoActivity.class);
            startActivity(i);
            return true;
        case R.id.menu_item_shoppingBasket:
            i = new Intent(getApplicationContext(), BasketActivity.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private void startBarcodeScanner() {
        Intent i = new Intent(getApplicationContext(), CaptureActivity.class);
        startActivity(i);
    }

    private void populateLists() {
        ArrayList<String> listTitle = new ArrayList<String>();
        ArrayList<String> listDetail = new ArrayList<String>();
        ArrayList<String> listText = new ArrayList<String>();
      
        cursor = db.getItemsInBasket();
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            String tmpDate = cursor.getString(0);

            int counter = 0;
            do {
                if (tmpDate.equals(cursor.getString(0))) {
                    counter++;
                } else {
                    listTitle.add(tmpDate);
                    listDetail.add(counter + (counter > 1 ? " varer " : " vare ")
                                    + "i indkøbskurven.");
                    listText.add(Integer.toString(getShoppingBasketRatingFromDate(tmpDate)));
                    counter = 1;
                    tmpDate = cursor.getString(0);
                }
            } while (cursor.moveToNext());

            if (counter != 0) {
                listTitle.add(tmpDate);
                listDetail.add(counter + (counter > 1 ? " varer " : " vare ") + "i indkøbskurven.");
                listText.add(Integer.toString(getShoppingBasketRatingFromDate(tmpDate)));
            }

            if (!listTitle.isEmpty() && !listDetail.isEmpty()) {
                title = listTitle.toArray(new String[listTitle.size()]);
                detail = listDetail.toArray(new String[listDetail.size()]);
                text = listText.toArray(new String[listText.size()]);
            }
        } else {
            Toast.makeText(getApplicationContext(), "Ingen historik fundet.", Toast.LENGTH_LONG)
                            .show();
        }
    }
    
    public int getShoppingBasketRatingFromDate(String date) {
        float fat = 0f;
        float saturatedFat = 0f;
        float monoUnsaturatedFat = 0f;
        float polyUnsaturatedFat = 0f;
        float protein = 0f;
        float carbonHydrate = 0f;
        float sugar = 0f;
        float alcohol = 0f;
        float ash = 0f;
        float water = 0f;

        Cursor cursor = db.getNutrientsFromFoodIdForRating(date);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                int compId = Integer.parseInt(cursor.getString(0));
                switch (compId) {
                case 1:
                    protein += Float.parseFloat(cursor.getString(1));
                    break;
                case 3:
                    fat += Float.parseFloat(cursor.getString(1));
                    break;
                case 4:
                    saturatedFat += Float.parseFloat(cursor.getString(1));
                    break;
                case 5:
                    monoUnsaturatedFat += Float.parseFloat(cursor.getString(1));
                    break;
                case 6:
                    polyUnsaturatedFat += Float.parseFloat(cursor.getString(1));
                    break;
                case 8:
                    carbonHydrate += Float.parseFloat(cursor.getString(1));
                    break;
                case 9:
                    sugar += Float.parseFloat(cursor.getString(1));
                    break;
                case 11:
                    alcohol += Float.parseFloat(cursor.getString(1));
                    break;
                case 12:
                    ash += Float.parseFloat(cursor.getString(1));
                    break;
                case 13:
                    water += Float.parseFloat(cursor.getString(1));
                    break;
                default:
                    break;
                }
            }
        }
        
        float total = fat + protein + carbonHydrate + alcohol + ash + water;
        
        fat = fat / total * 100;
        saturatedFat = saturatedFat / total * 100;
        monoUnsaturatedFat = monoUnsaturatedFat / total * 100;
        polyUnsaturatedFat = polyUnsaturatedFat / total * 100;
        protein = protein / total * 100;
        carbonHydrate = carbonHydrate / total * 100;
        sugar = sugar / total * 100;
        
        return FoodRating.calculateRating(fat, saturatedFat, monoUnsaturatedFat,
                        polyUnsaturatedFat, protein, carbonHydrate, sugar);
    }
}